#include "main.h"

rfid_info_t rfid_card;
act_timer_t act_timer;
dht11_data_t dht11;
eeprom_data_t edata;

//重启mcu
void System_SoftReset(void)
{
    __set_FAULTMASK(1); //关闭所有中断 
    NVIC_SystemReset(); //复位
}

void CueTone(uint16_t tone)
{
    PWM_SetFreq(tone);
    TIM_Cmd(TIM3, ENABLE);
}

void System_Init(eeprom_data_t *edata)
{
    uint8_t error = 0;
    
    edata->system.heartbeat = 10;
    edata->scanner.cmd00 = SCAN_CMD00;
    edata->scanner.cmd05 = SCAN_CMD05;
    edata->scanner.cmd06 = SCAN_CMD06;
    edata->scanner.cmd0d = SCAN_CMD0D;
    edata->scanner.cmd0f = SCAN_CMD0F;
    edata->scanner.cmd10 = SCAN_CMD10;
    edata->scanner.cmd60 = SCAN_CMD60;
    EEPROM_Init(edata);                               //初始化EEPROM或读取EEPROM数据
    act_timer.heartbeat = edata->system.heartbeat;    //刷新心跳间隔

    for(uint8_t i=0; i<sizeof(scanner_cmd_t)/2; i++)
    {
        if(SCAN_WriteCmd(*((uint16_t *)(&edata->scanner)+i) >> 8, *((uint16_t *)(&edata->scanner)+i)))  error++;
    }
    if(SCAN_SaveCmd())  error++;
    
    if(error)   UART_Printf(SERIAL, "Scanner init failed!");
}

uint8_t RFID_Get(void)
{
    if(!act_timer.rfid)
    {
        uint8_t status = PcdRequest(REQ_ALL,rfid_card.tag_type.array);
        if(!status)
        {
            status = PcdAnticoll(rfid_card.sn_code.array);
            if(!status)
            {
                act_timer.rfid = Interval;
                if(rfid_card.sn_now != rfid_card.sn_code.data)
                {
                    CueTone(H7);
                    rfid_card.sn_now = rfid_card.sn_code.data;
                    return 1;
                }
                else
                {
                    CueTone(H1);
                }
            }
        }
    }
    return 0;
}

uint8_t DHT11_Get(void)
{
    if(!act_timer.dht11)
    {
        uint8_t status = DHT11_Read_Data(&dht11.temp, &dht11.humi);
        if(!status)
        {
            dht11.temp = 0;
            dht11.humi = 0;
        }
        act_timer.dht11 = Interval;
        return status;
    }
    return 0;
}

void Push_Message(void)
{
    if(RFID_Get())      //获取到ic卡
    {
        uart_msg.serial.payload[0] = 0x4c;
        uart_msg.serial.payload[1] = 0x01;
        uart_msg.serial.payload[2] = 4;
        for(uint8_t i=0; i<4; i++)
        {
            uart_msg.serial.payload[3+i] = rfid_card.sn_code.array[3-i];
        }
        UART_SendArray(SERIAL, uart_msg.serial.payload, 7);
        //UART_Printf(SERIAL, "ID: %d", rfid_card.sn_code.data);    //以10进制方式打印id卡号
    }
    if(Scanner_Get())   //获取到条码信息
    {
        uart_msg.serial.payload[0] = 0x4c;
        uart_msg.serial.payload[1] = 0x02;
        uart_msg.serial.payload[2] = uart_msg.scanner.length;
        for(uint8_t i=0; i<uart_msg.scanner.length; i++)
        {
            uart_msg.serial.payload[3+i] = uart_msg.scanner.payload[i];
        }
        UART_SendArray(SERIAL, uart_msg.serial.payload, uart_msg.scanner.length + 3);
    }
    if(RS485_Get())     //获取到rs485总线数据
    {
        UART_SendArray(SERIAL, uart_msg.rs485.payload, uart_msg.rs485.length);
    }
    DHT11_Get();        //获取温湿度数据
    if(!act_timer.heartbeat && edata.system.heartbeat)    //处理心跳
    {
        act_timer.heartbeat = edata.system.heartbeat;    //重置心跳
        uart_msg.serial.payload[0] = 0x4c;
        uart_msg.serial.payload[1] = 0x00;
        uart_msg.serial.payload[2] = 0x04;
        for(uint8_t i=0; i<4; i++)
        {
            uart_msg.serial.payload[3+i] = *(((uint8_t *)&dht11)+i);
        }
        UART_SendArray(SERIAL, uart_msg.serial.payload, 7);
    }
}

void Received_Message(void)
{
    if(Serial_Get())    //获取到串口信息
    {
        if(uart_msg.serial.payload[SDATA_HEAD_BIT] == SDATA_HEAD)
        {
            if(uart_msg.serial.payload[SDATA_TYPE_BIT] & 0X80)   //最高位为1则是上位机发送的数据
            {
                dataTypeChange_t type_change;
                uart_msg.serial.payload[SDATA_TYPE_BIT] &= 0x7f; //清空最高位
                switch(uart_msg.serial.payload[SDATA_TYPE_BIT])
                {
                    case 0: //系统相关
                        if(uart_msg.serial.payload[SDATA_START_BIT] == 0x00)    //重启stm32
                        {
                            UART_Printf(SERIAL, "OK. The system restarts\r\n");
                            System_SoftReset();
                        }
                        if(uart_msg.serial.payload[SDATA_START_BIT] == 0x01)    //打印EEPROM
                        {
                            EEPROM_ContinuousRead(EE_DATA_START, (uint8_t *)&edata, sizeof(eeprom_data_t));   //读取EEPROM
                            UART_Printf(SERIAL, "OK. EEPROM data:\r\n");
                            for(uint8_t i=0; i<sizeof(eeprom_data_t); i++)
                            {
                                printf("%02x ", *((uint8_t *)&edata + i));
                            }
                            printf("\r\n");
                        }
                        else if(uart_msg.serial.payload[SDATA_START_BIT] == 0x02) //设置心跳
                        {
                            type_change.u8[1] = uart_msg.serial.payload[SDATA_START_BIT + 1];
                            type_change.u8[0] = uart_msg.serial.payload[SDATA_START_BIT + 2];
                            edata.system.heartbeat = type_change.u16[0];
                            if(edata.system.heartbeat > HEARTBEAT_MAX)   edata.system.heartbeat = HEARTBEAT_MAX;  //限制最大心跳
                            EEPROM_ContinuousWrite(EE_DATA_START, (uint8_t *)&edata, sizeof(eeprom_data_t));    //写入eeprom
                            
                            act_timer.heartbeat = 0;    //使修改立刻生效
                            if(edata.system.heartbeat)   UART_Printf(SERIAL, "OK. Heartbeat: %ds\r\n", edata.system.heartbeat);
                            else    UART_Printf(SERIAL, "OK. Heartbeat closed\r\n");
                        }
                        break;
                    case 1: //扫描器相关
                        if(uart_msg.serial.payload[SDATA_START_BIT] == 0x00) //恢复出厂设置
                        {
                            if(SCAN_FactoryReset()) UART_Printf(SERIAL, "ERR! Scanner factory reset failed\r\n");
                            else    UART_Printf(SERIAL, "OK. Scanner factory reset\r\n");
                        }
                        else if(uart_msg.serial.payload[SDATA_START_BIT] == 0x01)    //读扫描器寄存器
                        {
                            type_change.u8[0] = SCAN_ReadCmd(uart_msg.serial.payload[SDATA_START_BIT + 1]);
                            if(type_change.u8[0] == 0xff)   UART_Printf(SERIAL, "ERR! Scanner REG: %02x read failed\r\n", uart_msg.serial.payload[SDATA_START_BIT + 1]);
                            else    UART_Printf(SERIAL, "OK. Scanner REG: %02x VAL: %02x\r\n", uart_msg.serial.payload[SDATA_START_BIT + 1], type_change.u8[0]);
                        }
                        else if(uart_msg.serial.payload[SDATA_START_BIT] == 0x02)    //写扫描器寄存器
                        {
                            type_change.u8[1] = uart_msg.serial.payload[SDATA_START_BIT + 1];       //获取地址
                            type_change.u8[0] = uart_msg.serial.payload[SDATA_START_BIT + 2];       //获取数据
                            SCAN_WriteCmd(type_change.u8[1], type_change.u8[0]);
                            SCAN_SaveCmd();

                            UART_Printf(SERIAL, "OK. Scanner addr: %02x, data: %02x\r\n", type_change.u8[1], SCAN_ReadCmd(type_change.u8[1]));
                        }
                        else if(uart_msg.serial.payload[SDATA_START_BIT] == 0x03)   //基础设置
                        {
                            if(uart_msg.serial.payload[SDATA_START_BIT + 1] == 0x00)    //静音
                            {
                                if(uart_msg.serial.payload[SDATA_START_BIT + 2])
                                {
                                    BIT_CLEAR(edata.scanner.cmd00, SCAN_MUTE_BIT);
                                    UART_Printf(SERIAL, "OK. Scanner turn on mute\r\n");
                                }
                                else
                                {
                                    BIT_SET(edata.scanner.cmd00, SCAN_MUTE_BIT);
                                    UART_Printf(SERIAL, "OK. Scanner turn off mute\r\n");
                                }
                            }
                            else if(uart_msg.serial.payload[SDATA_START_BIT + 1] == 0x01)//定位灯
                            {
                                if(uart_msg.serial.payload[SDATA_START_BIT + 2] == 0x00) //关闭定位灯
                                {
                                    REG_MODIFY(edata.scanner.cmd00, SCAN_LOCATOR_LIGHT_BIT, 0x00);
                                    UART_Printf(SERIAL, "OK. Scanner turn off locator light\r\n");
                                }
                                else if(uart_msg.serial.payload[SDATA_START_BIT + 2] == 0x01)//拍照时闪烁
                                {
                                    REG_MODIFY(edata.scanner.cmd00, SCAN_LOCATOR_LIGHT_BIT, 0x10);
                                    UART_Printf(SERIAL, "OK. Scanner locator light flicker when taking photos\r\n");
                                }
                                else if(uart_msg.serial.payload[SDATA_START_BIT + 2] == 0x02)//常亮
                                {
                                    REG_MODIFY(edata.scanner.cmd00, SCAN_LOCATOR_LIGHT_BIT, 0x20);
                                    UART_Printf(SERIAL, "OK. Scanner turn on locator light\r\n");
                                }
                                else if(uart_msg.serial.payload[SDATA_START_BIT + 2] == 0x03)//拍照时常亮
                                {
                                    REG_MODIFY(edata.scanner.cmd00, SCAN_LOCATOR_LIGHT_BIT, 0x30);
                                    UART_Printf(SERIAL, "OK. Scanner turn on locator light when taking photos\r\n");
                                }
                            }
                            else if(uart_msg.serial.payload[SDATA_START_BIT + 1] == 0x02)//补光灯
                            {
                                if(uart_msg.serial.payload[SDATA_START_BIT + 2] == 0x00) //关闭补光灯
                                {
                                    REG_MODIFY(edata.scanner.cmd00, SCAN_FILL_LIGHT_BIT, 0x00);
                                    UART_Printf(SERIAL, "OK. Scanner turn off fill light\r\n");
                                }
                                else if(uart_msg.serial.payload[SDATA_START_BIT + 2] == 0x01)//拍照时点亮
                                {
                                    REG_MODIFY(edata.scanner.cmd00, SCAN_FILL_LIGHT_BIT, 0x04);
                                    UART_Printf(SERIAL, "OK. Scanner fill light up when taking photos\r\n");
                                }
                                else if(uart_msg.serial.payload[SDATA_START_BIT + 2] == 0x02)//常亮
                                {
                                    REG_MODIFY(edata.scanner.cmd00, SCAN_FILL_LIGHT_BIT, 0x08);
                                    UART_Printf(SERIAL, "OK. Scanner turn on fill light\r\n");
                                }
                            }
                            SCAN_WriteCmd(SCAN_CMD00_ADDR, edata.scanner.cmd00);
                            SCAN_SaveCmd();
                        }
                        //查询并保存到EEPROM
                        for(uint8_t i=0; i<sizeof(scanner_cmd_t)/2; i++)
                        {
                            *(((uint16_t *)&edata.scanner)+i) &= 0xff00;
                            *(((uint16_t *)&edata.scanner)+i) |= (uint16_t)SCAN_ReadCmd(*((uint16_t *)&edata.scanner+i) >> 8);
                        }
                        EEPROM_ContinuousWrite(EE_DATA_START, (uint8_t *)&edata, sizeof(eeprom_data_t));    //写入eeprom
                        break;
                    case 2: //暂无
                        
                        break;
                    default:
                        UART_Printf(SERIAL, "NOTE. This is a test message\r\n");
                        break;
                }
            }
        }
    }
}

int main(void)
{
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
    RCC_APB2PeriphClockCmd(LED_CLK, ENABLE);
    GPIO_InitConfig(LED_PORT, LED_PIN, GPIO_Mode_Out_OD, GPIO_Speed_2MHz);
    
    UART1_Serial_Init(115200);
    UART2_Scanner_Init(9600);
    UART3_RS485_Init(115200);
    
    TIM_Init();
    RC522_Init();
    DHT11_Init();
    Buzz_Init();
    
    delay_ms(1500);
    System_Init(&edata);
    LED_ON;
    IWDG_Init(1000);
    UART_Printf(SERIAL, "System init complete.\r\n");
    
	while(1) 
	{
        Push_Message();
        Received_Message();
        IWDG_ReloadCounter();
    }
}
//全局定时器
void TIM2_IRQHandler(void)
{
    if(TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)
    {
        if(edata.system.heartbeat)
            if(act_timer.heartbeat > 0)
                act_timer.heartbeat--;  //心跳
        if(act_timer.rfid > 0)  act_timer.rfid--;           //扫描间隔
        if(act_timer.dht11 > 0)  act_timer.dht11--;         //采集间隔
        TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
    }
}

//提示音
void TIM3_IRQHandler(void)
{
    if(TIM_GetITStatus(TIM3, TIM_IT_Update) == SET)
    {
        TIM_Cmd(TIM3, DISABLE);
        PWM_SetFreq(Z0);
        TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
    }
}
